<?php

use com\gdl\newagk\interfaces\InvcodeServiceIf;
use com\gdl\common\dataobject\common\ResultDO;
use com\gdl\newagk\dataobject\invcode\InvcodeDTO;
use com\gdl\newagk\dataobject\invcode\InvcodeRequestDTO;


class api_InvcodeService extends api_Abstract implements InvcodeServiceIf
{
	//生成二维码
    public function inback(InvcodeRequestDTO $Invcode)
    {
        $result = new ResultDO();
        try {

			$username = $Invcode->username ? $Invcode->username : '*';
			$reg = $Invcode->field ? $Invcode->field : '*';
			$code = sha1(md5($username.time().$reg));
			$code = substr($code,0,6);
			$PlaformInvitecode = new model_newagk_usercompany();
			$invcode =  $PlaformInvitecode->selectOne(['code'=>$code,'status'=>1],'id');
			if($invcode['id']!=''){
			   $code=$code.$reg;
			}
			
			$result->data[] = ['code'=>$code];
            if ($result) {
                $result->code = 1;
            } else {
                $result->code = 0;
            } 
			
            $result->success = true;
            return $result;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;
    }
	
	//通过邀请码添加平台
	 public function platformInviteCodeConfirm(InvcodeDTO $Invcode)
    {
		$result = new ResultDO();
		$userid = $Invcode->id ? gdl_lib_BaseUtils::getStr($Invcode->id, 'int') : '0';
		$code = $Invcode->code ? gdl_lib_BaseUtils::getStr($Invcode->code, 'string') : '';
        try {
            $modelPlaformInviteCode = new model_newagk_platforminvitecode();
            $modelUserCompany = new model_newagk_usercompany();
            $modelPlaform = new model_newagk_platform();
            $res = $modelPlaformInviteCode->selectOne(['code' => $code], 'id,code,platform_id,expire_time,status', '', 'order by id desc');
            if ($res['id']) {
                if ($this->_time < $res['expire_time'] && $res['status'] == '1') {
                    //开始绑定
                    $results = $modelUserCompany->isUserCompanyInfo($userid,0,$res['platform_id']);
                    if (empty($results['admin_reg'])) {
                        $re = $modelPlaform->getInfoById($res['platform_id'], 'admin_reg');
                        $insert = [
                            'userid' => $userid,
                            'platform_id' => $res['platform_id'],
                            'admin_reg' => $re['admin_reg']
                        ];
                        $ret = $modelUserCompany->insert($insert);


                        if ($ret) {

                            $result->code = 1;
                            $result->data[][] = $res['code'];
                            $result->message = '绑定成功';
                        } else {
                            $result->code = 0;
                            $result->message = '绑定失败';
                        }
                    } else {
						if($results['isdelete']){
							$ret = $modelUserCompany->insert($insert);
							$res = $modelEventDoc->update("userid='{$userid}' and platform_id='".$res['platform_id']."' and admin_reg='".$re['admin_reg']."'", 'isdelete=0');
            
							$result->code = 1;
                            $result->data[][] = $res['code'];
                            $result->message = '绑定成功';
						} else {
							$result->code = 0;
							$result->message = '您已添加过此平台';
						}
                    }
                } else {
                    $result->code = 0;
                    $result->message = '邀请码已过期';
                }
            } else {
                $result->code = 0;
                $result->message = '邀请码不存在';
            }
            $result->success = true;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
        }
        return $result;
    }
	
	//查询平台邀请码
	 public function lookeCode(InvcodeRequestDTO $Invcode)
    {
		$result = new ResultDO();
		$reg = $Invcode->field ? gdl_lib_BaseUtils::getStr($Invcode->field, 'string') : '';
		
		if($reg==''){
			$result->code = 0;
			$result->message = '缺少参数';
			$result->success = true;
			return $result;
		}
        try {
            $modelPlaformInviteCode = new model_newagk_platforminvitecode();
            $modelPlaform = new model_newagk_platform();
			$Plaform =  $modelPlaform->selectOne(['admin_reg' => $reg], 'id');
			if(empty($Plaform['id'])){
				$result->code = 0;
				$result->message = '平台不存在';
				$result->success = true;
				return $result;
			}
			
			
            $res = $modelPlaformInviteCode->select(['platformId' => $Plaform['id']], 'id,code,qrCode,status')->items;
	
            if ($res){
                
                    $result->data =  $res;
                    $result->message = '成功';
                
            } else {
                $result->code = 0;
                $result->message = '失败';
            }
            $result->success = true;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
        }
        return $result;
    }
	
	/**
     * 取得相关平台
     * @param type $platformType
     * @param type $name
     * @return ResultDO
     */
    public function getPlaform($platform_id, $filename,$userid = 0,$level)
    {

            $data = [];
            $ids = [];
            $condition = array();
            $result = new ResultDO();
            $userid = $userid ? gdl_lib_BaseUtils::getStr($userid, 'int') : 0;
			$platform_id = $platform_id ? gdl_lib_BaseUtils::getStr($platform_id, 'int') : 0;
			$modelPlaform = new model_newagk_platform();
			$usercompany = new model_newagk_usercompany();
            $leftJoin = array(
                $usercompany->tableName().' as b' => $modelPlaform->tableName().'.id=b.platform_id'
            );
			

			$page = ($filename['page']-1) * $filename['pagesize'];
			
            $condition = $modelPlaform->tableName().'.parentid='.$platform_id.' and '.$modelPlaform->tableName().'.isdelete=0';
			if(!empty($filename['title'])){
				$condition .= ' and '.$modelPlaform->tableName().".reals like'%".$filename['title']."%'";
			}
			if($filename['status']=='start'){
				$condition .= ' and '.$modelPlaform->tableName().'.status=1';
			} else if($filename['status']=='ends'){
				$condition .= ' and '.$modelPlaform->tableName().'.status=0';
			}
			
			
            $items =  $modelPlaform->tableName().'.id,'.$modelPlaform->tableName().'.reals,'.$modelPlaform->tableName().'.status,'.$modelPlaform->tableName().'.remark,count(b.id) num,FROM_UNIXTIME('.$modelPlaform->tableName().'.create_time) create_time';
            $groupBy = 'group by '.$modelPlaform->tableName().'.id  order by '.$modelPlaform->tableName().'.id desc  limit '.$page.','.$filename['pagesize'];

            try {
				$num = $modelPlaform->selectOne($condition, 'count(*) num');
                $res = $modelPlaform->select($condition, $items, $groupBy, '', $leftJoin)->items;
				
                //进行平台顶级读取处理

                if ($res) {
                    $result->data = $res;
					$result->message = $num['num'];
                    $result->code = 1;

                } else {
                    $result->code = 0;
					 $result->message = 0;
                }
                $result->success = true;
                return $result;
            } catch (Exception $e) {
                $result->success = false;
                $result->code = $e->getCode();
                $result->message = $e->getMessage();
            }
            return $result;

    }
	
	//生成平台
    public function platformAdd(InvcodeRequestDTO $Invcode)
    {
        $result = new ResultDO();
        try {
			$platform = new model_newagk_platform();
			$level = $platform->selectOne(['id'=>$data['platform_id']],'level,reals');
			$data = $Invcode->filename ? $Invcode->filename : [];

			
			$reg = self::get_random().$data['name'];
			$datas['admin_reg'] = $reg;
			$datas['name'] = $data['name'];
			$datas['admin_realname'] = $data['platform_id'] ? $level['reals'] : $data['real'];
			$datas['create_time'] = time();
            $datas['update_time'] = time();
			$datas['parentid'] =  $data['platform_id'];
			$datas['reals'] = $data['real'];
			$datas['status'] =  $data['status'];
			$datas['build'] =  $data['build'];
			$datas['logo'] =  $data['logo'];
			$datas['remark'] =  $data['remark'];
			
            $datas['level'] =  !empty($level) ? $level['level']+1 : 0;
			$id =$platform->insert($datas)->items;

            if ($id) {
                $result->code = 1;
				$result->message = '添加成功';
            } else {
                $result->code = 0;
				$result->message = '添加失败';
            } 
			
            $result->success = true;
            return $result;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;
    }
	
	// 查看 修改 平台
    public function platformEdit(InvcodeRequestDTO $Invcode)
    {
        $result = new ResultDO();
        try {
			$platform = new model_newagk_platform();
			$platform_id = $Invcode->platform ? $Invcode->platform : 0;
			$data = $Invcode->filename ? $Invcode->filename : [];
			
			if($platform_id){
				//查询
				$data = $platform->select(['id'=>$platform_id], 'reals,remark,status,build,logo')->items;
				$result->data = $data;
				
			} else {
				//修改
				if($data['platform_id']){
					$datas['reals'] = $data['name'];
					$datas['remark'] = $data['remark'];
					$datas['status'] = $data['status'];
					$datas['build'] = $data['build'];
					$datas['logo'] = $data['logo'];
					$platform->update(['id'=>$data['platform_id']],$datas);
				}
			}
            if ($data) {
                $result->code = 1;
				$result->message = '操作成功';
            } else {
                $result->code = 0;
				$result->message = '操作失败';
            } 
			
            $result->success = true;
            return $result;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;
    }
	
	// 修改 平台状态
    public function platformStatus(InvcodeRequestDTO $Invcode)
    {
        $result = new ResultDO();
        try {
			$platform = new model_newagk_platform();
			$platform_id = $Invcode->platform_id ? $Invcode->platform_id : 0;
			$filename = $Invcode->filename ? $Invcode->filename : [];
			$res = 0;
			if(!empty($filename)){
				$res = $modelEventDoc->update('id in('.$platform_id.')',$filename);
			}
            if ($res) {
                $result->code = 1;
				$result->message = '操作成功';
            } else {
                $result->code = 0;
				$result->message = '操作失败';
            } 
			
            $result->success = true;
            return $result;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;
    }
	
	// 保持二维码
    public function saveCode(InvcodeRequestDTO $Invcode)
    {
        $result = new ResultDO();
        try {
			$platform = new model_newagk_platform();
			$platforminvitecode = new model_newagk_platforminvitecode();
			$code = $Invcode->filename['code'] ? gdl_lib_BaseUtils::getStr($Invcode->filename['code'], 'string') : '';
			$imgurl = $Invcode->filename['imgurl'] ? gdl_lib_BaseUtils::getStr($Invcode->filename['imgurl'], 'string') : '';
			$reg = $Invcode->filename['reg'] ? gdl_lib_BaseUtils::getStr($Invcode->filename['reg'], 'reg') : '';
			$status = $Invcode->filename['status'] ? gdl_lib_BaseUtils::getStr($Invcode->filename['status'], 'int') : 0;
			if($code=='' || $reg==''){
				$result->code = 0;
				$result->message = '缺少参数';
				$result->success = true;
				return $result;
			}
			$platformDel = $platform->selectOne(['admin_reg'=>$reg],'id,name');
			if(empty($platformDel['name'])){
				$result->code = 0;
				$result->message = '平台不存在';
			
				$result->success = true;
				return $result;
			}
			$invitecode = $platforminvitecode->selectOne(['platformId'=>$platformDel['id']],'id');
			
			$data['name'] = $platformDel['name'];//'邀请码平台名称',
			$data['platformId'] = $platformDel['id'];//'平台ID',
			$data['code'] = $code;//'邀请码',
			$data['expireTime'] = time()+890000;//'过期时间',
			$data['createTime'] = time();//'记录创建时间',
			$data['updateTime'] = time();//'记录更新时间',
			$data['status'] = $status;//'状态 1:启用 0:禁用 2:删除 ',
			$data['qrCode'] = $imgurl;//'二维码图片', //这个后面要做图片上传
			
			if(empty($invitecode['id'])){
				$platforminvitecode->insert($data);
			} else {
				$platforminvitecode->update(['id'=>$invitecode['id']],$data);
			}
			
           
                $result->code = 1;
				$result->message = '操作成功';
           //$result->message = json_encode($platforminvitecode);
			
            $result->success = true;
            return $result;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;
    }

	public function getTopPlaformIdbyId($parentid)
    {
        while ($parentid != 0){
            $model = new model_newagk_platform();
            $where = ['id' => $parentid];
            $items = 'id,parentid,`reals`';
            $res = $model->selectOne($where,$items);
            $parentid = $res['parentid'];
        }
        return ['id' => $res['id'] , 'real' => $res['reals']];
    }

    public function get_random($prefix = '') {
		return $prefix . base_convert(time() * 1000, 10, 36) . "_" . base_convert(microtime(), 10, 36) . uniqid();
	}

}
